<template>
  <div id="app" class="SkTemperatureDetail">
    <a-card>
      <a-row :gutter="12" type="flex">
        <a-col>
          <a-select
            default-value="0"
            v-model="dataForm.classId"
            class="class-select"
            style="width: 90px;"
            @change="getDetail('class')"
          >
            <a-select-option v-for="item in classList" :key="item.id" :value="item.id">
              {{ item.className }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col v-if="currentShow">
          <a-select
            v-model="dataForm.month"
            class="class-select"
            style="width: 140px;"
            placeholder="请选择本学期月份"
            @change="getDetail('month')"
          >
            <a-select-option v-for="item in currentMonthList" :key="item" :value="item">
              <span style="margin-right: 10px;">本学期</span> {{ item.substring(5,7) }} 月
            </a-select-option>
          </a-select>
        </a-col>
        <a-col v-if="dataForm.classId == '0'">
          <a-select
            v-model="dataForm.semesterId"
            class="class-select"
            style="width: 190px;"
            placeholder="请选择历史学期"
            allowClear
            @change="getDetail('sem')"
          >
            <!-- <a-select-option value="历史学期">
              历史学期
            </a-select-option> -->
            <a-select-option v-for="item in SemesterList" :key="item.id" :value="item.id">
              {{ item.semesterName }}
            </a-select-option>
          </a-select>
        </a-col>
        <!-- <a-col>
          <a-button @click="queryData">查询</a-button>
        </a-col> -->
      </a-row>
      <div class="left-circle-icon-box">
        <a-icon type="left-circle"  @click="closeTable" style="font-size: 22px;"/>
      </div>
      <a-table v-if="tableShow" :loading="tableLoading" style="margin-top:15px;" bordered :columns="columns" rowKey="classId" :data-source="dataSource" :scroll="{ x: columns > 10 ?3000:1500, y: 600 }"></a-table>
      <a-spin style="margin-top: 35px;" v-else :spinning="collapseLoading">
        <div v-if="stuTemperature.length!=0">
          <a-collapse accordion v-model="activeKey">
            <a-collapse-panel v-for="(item,index) in stuTemperature" :key="String(index)" :header="item.date" >
              <a-row :gutter="[16,16]">
                <div v-show="item.detail.length != 0">
                  <a-col :span="6" v-for="(j,index) in item.detail" :key="index">
                    <a-table  bordered :pagination="false"  :columns="stuColumns"  rowKey="examinationTime" :data-source="j.list" ></a-table>
                  </a-col>
                </div>
                <div v-show="item.detail.length == 0">
                  <a-col :span="24">
                    <a-empty />
                  </a-col>
                </div>
              </a-row>
            </a-collapse-panel>
          </a-collapse>
        </div>
        <a-empty v-else/>
      </a-spin>
    </a-card>
  </div>
</template>
<script>
import { skClassList,querySkSemester } from '@/api/management.js'
import { getAction } from "@/api/manage.js";
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil';
export default {
  name: 'SkTemperatureDetail',
  data() {
    return {
      dataForm:{
        classId:"0",
        month:undefined,
        semesterId:"历史学期"
      },
      columns:[],
      dataSource:[],
      stuTemperature:[],
      dataColumns:[],
      stuColumns:[
        {
          title:"姓名",
          align:"center",
          width:80,
          dataIndex:"studentName"
        },
        {
          title:"测量时间",
          align:"center",
          width:100,
          dataIndex:"examinationTime",
          customRender: function(text) {
            return text.substring(11,16)
          }
        },
        {
          title:"体温",
          align:"center",
          width:70,
          dataIndex:"temperature"
        }
      ],
      stuDataSource:[],
      classList:[],
      SemesterList:[],   //学期列表
      currentMonthList:[],    //本学期月份
      monthList:[],    
      currentShow:true,
      tableShow:true,
      collapseLoading:false,
      tableLoading:false,
      activeKey:["0"]
    }
  },
  props:{
    singleClassId:{
      type:String,
      default:""
    }
  },
  watch:{
    
  },
  components: {},

  filters: {},

  computed: {},

  async created() {
    this.dataForm.classId = this.singleClassId;
    await this.getClassList();
    await this.getSkSemester();
    await this.getDetail("class");
    
  },

  activated() {},

  mounted() {},

  methods: {
    // 关闭表格页面
    closeTable(){
      this.$emit("detailData",true);
      this.$emit("classData",{classId:"0"});
    },
    // 获取所有的班级
    getClassList() {
      return new Promise((resolve, reject) => {
        skClassList()
          .then(res => {
            if (res.success) {
              this.classList = res.result;
              this.classList.unshift({ className: '全园',id:"0" })
              resolve()
            } else {
              this.$message.warning(res.message)
            }
            this.classLoading = false;
          })
          .catch(error => {
            console.error(error)
          })
      })
    },
    // 学期列表
    getSkSemester() {
      return new Promise((resolve, reject) => {
        querySkSemester()
        .then(res => {
          if (res.success) {
            this.SemesterList = res.result.records
            this.getCurrentSemester()
            resolve()
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch(error => {
          console.error(error)
        })
      })
    },
    // 获取当前学期月份
    getCurrentSemester(){
      let month = this.$skCommon.getDate(0);
      // 转换时间戳
      let day = Date.parse(month);
      let Semester = this.SemesterList.find(item=>{
        if (this.dataForm.semesterId == "历史学期") {
          let time1 = Date.parse(item.startDate);
          let time2 = Date.parse(item.endDate);
          if (day > time1 && day < time2) {
            return item.id;
          }
        }else{
          return item.id == this.dataForm.semesterId
        }
      })
      // 判断寒暑假
      if (!Semester) {
        this.currentShow = false;
      }else{
        let startDate = Semester.startDate;
        let endDate = Semester.endDate;
        let monthList = this.$skCommon.getMonths(startDate,endDate);
        if (this.dataForm.semesterId == "历史学期") {
          this.currentMonthList = monthList
        }else{
          this.monthList = monthList;
        }
        this.dataForm.month = month.substring(0,7);
      }
    },
    
    // 查询按钮
    getDetail(value){
      if (value == "sem") {
        this.getCurrentSemester();
        this.dataForm.month = "本学期";
      }
      if ((value == "sem" && !this.dataForm.semesterId) || value == "month") {
        this.dataForm.semesterId = "历史学期"
      }
      if (this.dataForm.classId == "0") {
        this.getClassData();
        this.tableShow = true;
      }else{
        this.getStuList()
        this.tableShow = false;
      }
      //没有数据自动填充
      this.dataColumns = []
      this.activeKey = ["0"];
      // 获取当前月份
      let currentMonth = this.$skCommon.getDate(0).substring(0,7)
      if (currentMonth != this.dataForm.month) {
        // 获取指定月份所有的天数
        let days = this.$skCommon.getMonthDay(this.dataForm.month);
        for (let i = 1; i <= days; i++) {
          let day = i <= 9? "0" + i : i
          this.dataColumns.push(this.dataForm.month.substring(5)+"-"+day)
        }
      }else{
        // 获取当月天数
        this.dataColumns = this.$skCommon.getCurrentMonthDays();
      }
      this.dataColumns.reverse();
    },
    // 查询每个班级每天的体温数据
    getClassData(){
      return new Promise((resolve, reject) => {
        this.tableLoading = true;
        const url = "/health/skTemperatureRecord/getTotalTemperatureStatistical";
        let month = this.dataForm.month
        const params = {
          semesterId:this.dataForm.semesterId == "历史学期"?null:this.dataForm.semesterId,
          startDate:this.dataForm.semesterId == "历史学期"?month + "-01":null,
          endDate:this.dataForm.semesterId == "历史学期"?this.getLastDay(this.dataForm.month):null,
          byType:this.dataForm.semesterId == "历史学期"?"day":"month",
          statisticalScope:"class"
        }
        this.columns = [
          {
            title: '年级',
            align: 'center',
            fixed: 'left',
            dataIndex: 'classType',
            width:100,
            customRender: function(text) {
              return filterDictTextByCache('class_type', text)
            }
          },
          {
            title: '班级',
            fixed: 'left',
            align: 'center',
            width:100,
            dataIndex: 'className',
          },
        ]
        getAction(url,params).then((res)=>{
          if(res.success){
            this.dataSource = [];
            this.classList.forEach(el => {
              if (el.id !=0) {
                let classItem = {}
                classItem = {
                  classId: el.id,
                  className: el.className,
                  classType: el.classType
                }
                const classData = res.result.filter(item => {
                  return item.classId == el.id
                })
                if (this.dataForm.semesterId == "历史学期") {
                  for(let rowIndex = 0; rowIndex < this.dataColumns.length; rowIndex++){
                    const rowString = this.dataColumns[rowIndex].toString()
                    const monthData = classData.find(item => item.statisticalDate.substring(5) == rowString);
                    if(monthData){
                      classItem['actualNum' + rowString] = monthData.actualNum;
                      classItem['noTemperatureNum' + rowString] = monthData.noTemperatureNum;
                    }
                  }
                }else{
                  this.monthList.forEach(item=>{
                    const rowString = item.substring(5)
                    const monthData = classData.find(item => item.statisticalDate.substring(5) == rowString);
                    if (monthData) {
                      classItem['actualNum' + rowString] = monthData.actualNum;
                      classItem['noTemperatureNum' + rowString] = monthData.noTemperatureNum;
                    }
                  })
                }
                this.dataSource.push(classItem);
              }
            })
            if (this.dataForm.semesterId == "历史学期") {
              this.setColumns(this.dataColumns)
            }else{
              this.setColumns(this.monthList)
            }
            resolve()
          } else {
            this.message.warning(res.message);
          }
          this.tableLoading = false;
        }).catch((error)=>{
          console.error(error);
        })
      })
    },
    setColumns(dateArr){
      dateArr.forEach(item => {
        let json = {};
        let date = "",titleDate = ""
        if (this.dataForm.semesterId == "历史学期") {
          titleDate = item.substring(3);
          date = item;
        }else{
          titleDate = item.substring(5)
          date = item.substring(5);
        }
        json = {
          title:titleDate,
          align: 'center',
          children: [
            {
              title: `实测`,
              align: 'center',
              width:70,
              dataIndex: `actualNum${date}`,
              customRender: function(text) {
                return text > 0 ?text:0
              }
            },
            {
              title: `未测`,
              align: 'center',
              width:70,
              dataIndex: `noTemperatureNum${date}`,
              customRender: function(text) {
                return text > 0 ?text:0
              }
            }
          ]
        }
        this.columns.push(json)
      });
    },
    // 选择班级查询学生体温数据
    getStuList(){
      return new Promise((resolve, reject) => {
        this.collapseLoading = true;
        const url = "/health/skTemperatureRecord/getStudentAllTemperature";
        let month = this.dataForm.month
        const params = {
          classId:this.dataForm.classId,
          startDate:month + "-01",
          endDate:this.getLastDay(this.dataForm.month),
        }
        getAction(url,params).then((res)=>{
          if(res.success){
            this.stuTemperature = []
            if (res.result.length > 0) {
              this.dataColumns.forEach(el => {
                let newDateArr = [];
                let classItem = {
                  date:el,
                  detail:[]
                }
                res.result.filter(item=>{
                  if (item.statisticalDate.substring(5) == el) {
                    newDateArr.push(item)
                  }
                })
                let arrWarp = [],result = []
                for (let item of newDateArr) { // 遍历数组
                  if (!arrWarp.includes(item.studentName)) { // 判断根据哪个参数
                    let obj = {
                      list: [],
                    }
                    obj.list.push(item);
                    result.push(obj);
                    arrWarp.push(item.studentName);
                  } else {
                    result[arrWarp.indexOf(item.studentName)].list.push(item);
                  };
                };
                classItem.detail = result;
                this.stuTemperature.push(classItem)
              });
            }
            resolve()
          } else {
            this.message.warning(res.message);
          }
          this.collapseLoading = false;
        }).catch((error)=>{
          console.error(error);
        })
      })
    },
    // 获取下个月第一天
    getLastDay(startDate) {
      var year = '';
      var date = new Date();
      var currentMonth = Number(startDate.substring(5));
      var nextMonth = currentMonth;
      var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      var lastTime = new Date(nextMonthFirstDay);
      var month = parseInt(lastTime.getMonth() + 1);
      var day = lastTime.getDate();
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      if (currentMonth === 12) {
        year = date.getFullYear() + 1
      } else {
        year = date.getFullYear()
      }
      return year + '-' + month + '-' + day;
    }
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.left-circle-icon-box{
  display: flex;
  justify-content: end;
  margin:10px 0;
  cursor: pointer;
}
</style>
